<?php

namespace App\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\VoucherResource;
use App\Models\User;
use App\Models\Voucher;
use Illuminate\Http\Request;

class VoucherController extends Controller
{

    public function index()
    {
        return VoucherResource::collection(Voucher::paginate(5));
    }


    /**
     * 卡券拥有的记录,用于展示流通记录
     * @param Voucher $voucher
     * @return mixed
     */
    public function haveRecords(Request $request, Voucher $voucher)
    {
        return $voucher->records->load('user');
//        return $voucher->load('records.user');
    }

    //用户拥有的代金券
    public function userHasVouchers(User $user)
    {
        return $user->vouchers;
    }

    /**
     * 批量生成代金券
     * @param Request $request
     * @param User $user
     * @return array
     */
    public function patch(Request $request, Voucher $voucher)
    {
        $i = $request->number;
        $description = $request->description;
        while ($i > 0) {
            $voucher->create(['user_id' => $request->user_id, 'description' => $description]);
            $i--;
        }
        return $this->message('添加成功');
    }

    /**
     * 单个生成代金券
     * @param Request $request
     * @param Voucher $voucher
     * @return array
     */
    public function store(Request $request, Voucher $voucher)
    {
        $voucher->create($request->except(['user_name', 'statusTitle']));
        return $this->message('保存成功');
    }


    /**
     * 可兑换代金券，转移3次且状态为非
     * @return mixed
     */
    public function exchangeable()
    {
        //状态是2时可以兑换
        return VoucherResource::collection(Voucher::where('status', '=', 2)->paginate(5));
    }


    public function show(Voucher $voucher)
    {

        return new VoucherResource($voucher);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param \App\Models\Voucher $voucher
     * @return \Illuminate\Http\Response
     */
    public function edit(Voucher $voucher)
    {
        return new VoucherResource($voucher);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param \App\Models\Voucher $voucher
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Voucher $voucher)
    {
        $voucher->update($request->except(['user_name', 'statusTitle']));

        return $this->message('保存成功');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param \App\Models\Voucher $voucher
     * @return \Illuminate\Http\Response
     */
    public function destroy(Voucher $voucher)
    {
        $voucher->delete();
        return $this->message('删除成功');
    }
}
